// var express = require('express');
// var router = express.Router();
// var Reviews = require("../data/reviews")
// var Books = require("../data/books")

const express = require('express');
const router = express.Router();
const data = require('../data');
const Books = data.books;
const Reviews = data.reviews;

router.post('/:bookId', async function (req, res, next) {
  let booksData = {
    title: "the books scrdsd commeds",
    reviewer: "string---c",
    bookBeindReviewed: `${req.params.bookId}`,
    rating: 3,
    dateOfReview: "10/7/2020",
    review: "this books very cold"
  }
  let valid = await Reviews.validation(booksData)
  if (valid.flag) {
    let result = await Reviews.saveReviews(booksData)
    console.log(result)
    let pushId = await Books.updateReviews(req.params.bookId, result._id)
    res.json({ status: 1, msg: "review add success" })
  } else {
    console.log(valid.error)
    res.sendStatus(400)
    return
  }

});

router.get("/:bookId", async function (req, res, next) {
  try {
    // console.log(req.body)
    let result = await Reviews.findAll(req.params.bookId)
    res.json(result)
  } catch (err) {
    res.sendStatus(404)
    return
  }

})

router.get("/:bookId/:reviewId", async function (req, res, next) {
  try {
    let result = await Reviews.findOneReview(req.params.reviewId)
    res.json(result)
  } catch (err) {
    res.sendStatus(404)
    return
  }

})
router.delete("/:bookId/:reviewId", async function (req, res, next) {
  try {
    let result = await Reviews.deleteOneReview(req.params.reviewId, req.params.bookId)
    let resultbook = await Books.deleteOneReview(req.params.bookId, req.params.reviewId)
    res.json(result)
  } catch (err) {
    res.sendStatus(404)
    return
  }

})
module.exports = router;
